  <template>
  <el-dialog title="分配权限" :visible.sync="visible">
    <el-tree
      class="filter-tree"
      :data="dataTree"
      :props="defaultProps"
      node-key="ps_id"
      ref="tree"
      show-checkbox
      default-expand-all
      :expand-on-click-node="false"
      check-on-click-node
    >
    </el-tree>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="dispatchPerm()">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPermissionList, getPermListById, dispatchPerm } from "@/api/role";

export default {
  name: "DispatchPermDialog",
  data() {
    return {
      visible: false,
      dataTree: [
        // {
        //   ps_id: 1,
        //   ps_name: "商品管理",
        //   children: [
        //     {
        //       ps_id: 2,
        //       ps_name: "商品列表",
        //     },
        //   ],
        // },
      ],
      defaultProps: {
        children: "children", //指定节点指数对应的内容
        label: function (data, node) {
          //指定节点的显示内容 这里显示label
          return `${data.ps_name}(${data.ps_id})`;
        },
      },
      role_id: 0,
    };
  },
  mounted() {
    this.$bus.$on("showDispatchPermDialog", (row) => {
      this.visible = true;
      this.role_id = row.role_id;
      //获取全部的权限列表（用于显示）
      getPermissionList().then((res) => {
        this.dataTree = res.data.data;
      });
      //获取该角色的权限列表（用于显示tree）
      getPermListById(row.role_id).then((res) => {
        // console.log(res.data.data);
        this.$refs["tree"] && this.$refs["tree"].setCheckedKeys(res.data.data);
      });
    });
  },
  methods: {
    //   获取选中的keys
    getCheckedKeys() {
      //半选结点需要通过node获取 这里获取后需要进行遍历获取key
      let nodeList = this.$refs["tree"].getCheckedNodes(false, true);
      let keys = [];
      nodeList.forEach((item) => {
        keys.push(item.ps_id);
      });
      return keys;
    },
    //请求分配
    dispatchPerm() {
      //获取选中的结点的key（通过nodes遍历得到的key)
      let ps_ids = this.getCheckedKeys();
      //分配权限
      dispatchPerm(this.role_id, ps_ids).then(
        (res) => {
          if (res.data.status !== 200)
            return this.$message.error("权限分配失败");
          this.visible = false;
          this.$message.success("权限分配成功");
          // 要告诉TableList更新一下数据（因为扩展expand行数据 通过tableList获取）
          this.$bus.$emit("refreshRoleList");
        },
        (err) => {
          this.$message.error("权限分配失败");
        }
      );
    },
  },
};
</script>

<style  scoped>
</style>
